package org.eae.eldf.webapp.controller.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import org.eae.eldf.webapp.base.AbstractController;
import org.eae.eldf.webapp.common.bean.Result;
import org.eae.eldf.webapp.common.bean.ResultList;
import org.eae.eldf.webapp.common.constant.StateDefine;
import org.eae.eldf.webapp.vo.CheckboxZtreeVo;
import org.eae.eldf.webapp.vo.RolePurviewZtreeVo;
import org.eae.eldf.dto.sys.RolePurviewCheckDto;
import org.eae.eldf.dto.sys.SysOperatorQueryDto;
import org.eae.eldf.dto.sys.SysRoleQueryDto;
import org.eae.eldf.entity.sys.SysMenu;
import org.eae.eldf.entity.sys.SysOperator;
import org.eae.eldf.entity.sys.SysPurview;
import org.eae.eldf.entity.sys.SysRole;
import org.eae.eldf.framework.pager.Pagination;
import org.eae.eldf.framework.persistence.Criteria;
import org.eae.eldf.framework.annotation.Token;
import org.eae.eldf.framework.spring.SpringSecurityUtils;
import org.eae.eldf.service.sys.SysMenuService;
import org.eae.eldf.service.sys.SysPurviewService;
import org.eae.eldf.service.sys.SysRoleService;

@Controller
@RequestMapping("/sys")
public class SysRoleController extends AbstractController<SysRole>{

	private SysRoleService sysRoleService;
    @Autowired
	public void setSysRoleService(SysRoleService sysRoleService) {
		this.sysRoleService = sysRoleService;
	}
    
    
    private SysMenuService sysMenuService;
    
    @Autowired
    public void setSysMenuService(SysMenuService sysMenuService) {
		this.sysMenuService = sysMenuService;
	}


	private SysPurviewService sysPurviewService;

    @Autowired
	public void setSysPurviewService(SysPurviewService sysPurviewService) {
		this.sysPurviewService = sysPurviewService;
	}


	/**
     * 查询列表页面
     */
    @RequestMapping(value="/role")
    public String initPage(ModelMap modelMap,HttpServletRequest request,
    		HttpServletResponse response){
		return "/sys/role/sys_role";
    }
    
    /**
	 * 分页查询
	 * @param request
	 * @param response
	 * @param sysOperatorQueryDto
	 * @return
	 */
	@RequestMapping(value = "/role/list")
	public @ResponseBody ResultList<SysRole> pageList(
			HttpServletRequest request, 
			HttpServletResponse response,
			@ModelAttribute(value="sysOperatorQueryDto") SysRoleQueryDto sysRoleQueryDto){
		Pagination<SysRole> pager = super.newPaginationInstance(sysRoleQueryDto);
		pager = sysRoleService.pageRoleList(pager, sysRoleQueryDto);
		return outPageArrayList(pager,sysRoleQueryDto);
	}
    
   
    
    
    /**新增角色
     * @param role
     * @return
     */
    
    @RequestMapping(value="/role/add",method=RequestMethod.POST)
    @ResponseBody
    public Result insert(@RequestParam(required=false) String srolename,
    		@RequestParam(required=false) String sremark,
    		HttpServletRequest request){
    	Result result = new Result(StateDefine.FLAG_SUCCESS, true);
    	//查询角色名是否重复 若重复 给出提示 "角色名已经存在"
    	if (sysRoleService.queryCount(Criteria.create(SysRole.class).where("srolename", new Object[]{srolename}))>0) {
    		RequestContext context=new RequestContext(request);
			result.setResultValue(false);
			result.setMessage(context.getMessage("role.msg.srolename.exist"));
		}
    	else {
    		SysRole sysRole=new SysRole();
        	sysRole.setSrolename(srolename);
        	sysRole.setSremark(sremark);
        	sysRole.setDlastupdatetime(new Date());
        	sysRole.setSlastupdateuser(SpringSecurityUtils.getCurrentUserName());
        	sysRole.setDcreatetime(new Date());
        	sysRoleService.insert(sysRole);
		}
		return result;
    	
    }
    
    /**
     * 编辑角色
     * @param id
     * @param srolename
     * @param sremark
     * @param searchValue
	 * @param sorting_column_order
	 * @param sorting_asc_desc
	 * @return
     */
    @RequestMapping(value="/role/edit",method=RequestMethod.POST)
    @ResponseBody
    public Result update(@RequestParam(required=false) Long sysRoleId,
    		@RequestParam(required=false) String srolename,
    		@RequestParam(required=false) String sremark,
    		ModelAndView modelAndView){
    	Result result = new Result(StateDefine.FLAG_SUCCESS, true);
		sysRoleService.update(Criteria.create(SysRole.class)
				.set("srolename", srolename).set("sremark", sremark)
				.where("sysRoleId", new Object[]{sysRoleId}));
    	return result;
    	
    }
    
   
    /**
     *  删除角色
     */
    @RequestMapping(value="/role/del")
    public @ResponseBody Result delete(@RequestParam Long id){
    	Result result = new Result(StateDefine.FLAG_SUCCESS, true);
    	try {
    		sysRoleService.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return result;
    }
    
    
    
    //跳转到资源授权
	@RequestMapping(value="/role/purview")
	@ResponseBody
    public RolePurviewZtreeVo toAuth(@RequestParam Long id,
    		@RequestParam(required=false) String srolename,
    		ModelMap modelMap){
		RolePurviewZtreeVo v = new RolePurviewZtreeVo();
		//所有菜单
		List<SysMenu> menuList = sysMenuService.queryList(Criteria.create(SysMenu.class));
		
		//获取所有权限
		List<SysPurview> purList=  sysPurviewService.queryList(Criteria.create(SysPurview.class));
		
		// 构造tree
		Map<String, CheckboxZtreeVo> roleMap=new LinkedHashMap<String, CheckboxZtreeVo>();
		//查询角色对应的权限
		List<SysPurview> purviews=sysRoleService.queryPurviewByRole(id);
		List<Long> purids = new ArrayList<Long>();
		if (purviews != null) {
			for (SysPurview purview2 : purviews) {
				purids.add(purview2.getSysPurviewId());
			}
		}
		
		//菜单加入到treeMap 加menu_避免id重复
    	for(SysMenu menu:menuList){
    		//RolePurviewCheckDto rolePurviewCheckDto=new RolePurviewCheckDto();
    		CheckboxZtreeVo vo = new CheckboxZtreeVo();
    		vo.setpId(menu.getParentid()!=null?"menu_"+menu.getParentid().toString():null);
    		vo.setName(menu.getSname());
    		vo.setId(null);
    		vo.setLeaf(false);
    		
//    		rolePurviewCheckDto.setId("menu_"+menu.getSysMenuId().toString());
//    		rolePurviewCheckDto.setText(menu.getSname());
//    		rolePurviewCheckDto.setLeaf(false);
//    		rolePurviewCheckDto.setParentid(menu.getParentid()!=null?"menu_"+menu.getParentid().toString():null);
    		
    		roleMap.put("menu_"+menu.getSysMenuId().toString(), vo);
    	}
    	
    	
		for (SysPurview purview : purList) {
			CheckboxZtreeVo tree = new CheckboxZtreeVo();
			tree.setId(purview.getSysPurviewId());
			tree.setName(purview.getSpurname());
			tree.setpId("menu_"+purview.getParentid());
			tree.setLeaf(true);
			roleMap.put(purview.getSysPurviewId().toString(), tree);
		}
		CheckboxZtreeVo root = new CheckboxZtreeVo();
		// 递归构造树
		Iterator<Map.Entry<String, CheckboxZtreeVo>> it = roleMap.entrySet()
				.iterator();
		while (it.hasNext()) {
			Map.Entry<String, CheckboxZtreeVo> entry = it.next();
			CheckboxZtreeVo tree = entry.getValue();
			if (StringUtils.isBlank(tree.getpId())) {// 如果是根节点
				root.getChildren().add(tree);
			} else {
				CheckboxZtreeVo parent = roleMap.get(tree.getpId());// 根据父Id查询
				if (parent != null) {
					parent.getChildren().add(tree);
				}
			}
		}
		// 选中有权限码的节点及父节点
		  root.removeNoRight();
		v.setTreeData(root.getChildren());
		v.setPurviews(purids);
    	 return v;
    }
	
	

	
	//保存角色权限码
	@RequestMapping(value="/role/purviewSave",method=RequestMethod.POST)
	public  @ResponseBody Result savePurview(@RequestParam(required = false) Long id,
			@RequestParam(required = false) List<Long> purid,
			ModelAndView  modelAndView){
		Result result = new Result(StateDefine.FLAG_SUCCESS, true);
		sysRoleService.saveRolePurview(id, purid);
		return result;
	}
}
